package com.example.michong.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.michong.result.JsonResult;
import com.sun.management.OperatingSystemMXBean;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@RestController
@Api(value = "用户信息接口")
@RefreshScope
public class SysController {
    @Autowired
    RedisTemplate redisTemplate;

    private static OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();

    @GetMapping("/getUser/{id}")
//    @ApiOperation(value = "根据用户唯一标识获取用户信息")
    public JsonResult<String> getUserInfo(@PathVariable (value = "用户唯一 标识") String id) {
            return new JsonResult<String>(String.valueOf(id));
}
//
    @Value("${spring.redis.port}")
    private String port;

    /*@Value("${pattern.dateformat}")
    private String dateformat;*/


    @GetMapping("/getRedisInfo")
    public JsonResult<Map> getRedisInfo(){

       /* Properties memory = redisTemplate.getRequiredConnectionFactory().getConnection().info("all");

        Map<String,Object> map = new HashMap<>(1);

        map.put("memory" , memory);

        return new JsonResult<>(memory);*/

/*
        Properties memory = redisTemplate.getRequiredConnectionFactory().getConnection().info("Memory");

        String usedMemoryHuman = memory.getProperty("used_memory_human");

        String usedMemoryPeakHuman = memory.getProperty("used_memory_peak_human");

        double v = Float.parseFloat( usedMemoryHuman.substring(0, usedMemoryHuman.length()-1)) /
                Float.parseFloat(   usedMemoryPeakHuman.substring(0,usedMemoryPeakHuman.length()-1));

        String s = port;


        return new JsonResult<Double>(v);
*/
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", key);
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return new JsonResult<>(result);

    }
    @GetMapping("/getSysInfo")
    public  String getSysInfo(String[] args) {
        final long GB = 1024 * 1024 * 1024;
        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        String osJson = JSON.toJSONString(operatingSystemMXBean);
//            System.out.println("osJson is " + osJson);
        JSONObject jsonObject = JSON.parseObject(osJson);
        double processCpuLoad = jsonObject.getDouble("processCpuLoad") * 100;
        double systemCpuLoad = jsonObject.getDouble("systemCpuLoad") * 100;
        Long totalPhysicalMemorySize = jsonObject.getLong("totalPhysicalMemorySize");
        Long freePhysicalMemorySize = jsonObject.getLong("freePhysicalMemorySize");
        double totalMemory = 1.0 * totalPhysicalMemorySize / GB;
        double freeMemory = 1.0 * freePhysicalMemorySize / GB;
        double memoryUseRatio = 1.0 * (totalPhysicalMemorySize - freePhysicalMemorySize) / totalPhysicalMemorySize * 100;

        StringBuilder result = new StringBuilder();
        result.append("系统CPU占用率: ")
                .append(twoDecimal(systemCpuLoad))
                .append("%，内存占用率：")
                .append(twoDecimal(memoryUseRatio))
                .append("%，系统总内存：")
                .append(twoDecimal(totalMemory))
                .append("GB，系统剩余内存：")
                .append(twoDecimal(freeMemory))
                .append("GB，该进程占用CPU：")
                .append(twoDecimal(processCpuLoad))
                .append("%");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result.toString();
    }
    public static double twoDecimal(double doubleValue) {
        BigDecimal bigDecimal = new BigDecimal(doubleValue).setScale(2, RoundingMode.HALF_UP);
        return bigDecimal.doubleValue();
    }

    public static int memoryLoad() {
        double totalvirtualMemory = osmxb.getTotalPhysicalMemorySize();
        double freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize();

        double value = freePhysicalMemorySize/totalvirtualMemory;
        int percentMemoryLoad = (int) ((1-value)*100);
        return percentMemoryLoad;

    }

}
